package com.yihubang.taobaokotlin.ui.fragment

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.lcodecore.tkrefreshlayout.Footer.LoadingView
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.yihubang.taobaokotlin.R
import com.yihubang.taobaokotlin.base.BaseFragment
import com.yihubang.taobaokotlin.interfaces.ICategoryPageCallback
import com.yihubang.taobaokotlin.model.Categories
import com.yihubang.taobaokotlin.model.HomePagerContent
import com.yihubang.taobaokotlin.presenter.impl.CategoryPagePresenterImpl
import com.yihubang.taobaokotlin.ui.adapter.LinearItemContentAdapter
import com.yihubang.taobaokotlin.utils.UrlUtils
import com.zhouwei.mzbanner.MZBannerView
import com.zhouwei.mzbanner.holder.MZHolderCreator
import com.zhouwei.mzbanner.holder.MZViewHolder


/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/11.
 * PS: Not easy to write code, please indicate.
 */
class HomePagerFragment : BaseFragment(), ICategoryPageCallback {

    private var materialid: Int? = null
    private val datas = mutableListOf<HomePagerContent.DataBean>()
    private lateinit var homePagerRefresh: TwinklingRefreshLayout
    private lateinit var mAdapter: LinearItemContentAdapter
    private lateinit var headerView: View
    private lateinit var mMZBanner: MZBannerView<HomePagerContent.DataBean>

    companion object {
        private const val KEY_HOME_PAGER_TITLE = "KEY_HOME_PAGER_TITLE"
        private const val KEY_HOME_PAGER_MATERIAL_ID = "KEY_HOME_PAGER_MATERIAL_ID"

        @JvmStatic
        fun newInstance(categories: Categories.DataBean): HomePagerFragment {
            val homePagerFragment = HomePagerFragment()
            val bundle = Bundle().apply {
                putString(KEY_HOME_PAGER_TITLE, categories.title)
                putInt(KEY_HOME_PAGER_MATERIAL_ID, categories.id)
            }
            homePagerFragment.arguments = bundle
            return homePagerFragment
        }
    }

    override fun initView(rootView: View) {
        arguments?.apply {
            val title = getString(KEY_HOME_PAGER_TITLE)
            materialid = getInt(KEY_HOME_PAGER_MATERIAL_ID)
        }
        val recycler: RecyclerView = rootView.findViewById(R.id.home_pager_content_list)
        val layoutManager = LinearLayoutManager(activity)
        recycler.layoutManager = layoutManager
        mAdapter = LinearItemContentAdapter(R.layout.item_linear_goods_content, datas, context!!)
        headerView = LayoutInflater.from(activity).inflate(R.layout.header_home_banner, null)

        mAdapter.setHeaderView(headerView)
        recycler.adapter = mAdapter

        homePagerRefresh =
            rootView.findViewById(R.id.home_pager_refresh)
        //是否开启悬浮刷新模式(支持切换到像SwipeRefreshLayout一样的悬浮刷新模式),默认false
        homePagerRefresh.setFloatRefresh(true)

        //仿android原生系统下拉刷新 SwipeRefreshLayout
        val headerView = ProgressLayout(activity)
        homePagerRefresh.setHeaderView(headerView)
        homePagerRefresh.setBottomView(LoadingView(activity))

        homePagerRefresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                super.onRefresh(refreshLayout)
                Handler().postDelayed({
                    homePagerRefresh.finishRefreshing()
                }, 2000)
            }

            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                super.onLoadMore(refreshLayout)
                CategoryPagePresenterImpl.getLoadMore(materialid)
            }
        })
    }

    override fun getRootViewResId() = R.layout.fragment_home_pager

    override fun initPresenter() {
        CategoryPagePresenterImpl.registerViewCallback(this)
        CategoryPagePresenterImpl.getContentByCategoryId(materialid)
    }

    override fun release() {
        super.release()
        CategoryPagePresenterImpl.unregisterViewCallback(this)
    }

    override fun onContentLoaded(dataBean: MutableList<HomePagerContent.DataBean>) {
        //数据列表加载到了
        setUpState(State.SUCCESS)
        datas.addAll(dataBean)
    }

    override fun getCategoryId(): Int? {
        return materialid
    }

    override fun onLoaderMoreError() {
        Toast.makeText(activity, "网络错误，请稍后重试！", Toast.LENGTH_SHORT).show()
        finishLoadMore()
    }

    override fun onLoaderMoreEmpty() {
        Toast.makeText(activity, "没有更多商品！", Toast.LENGTH_SHORT).show()
        finishLoadMore()
    }

    override fun onLoaderMoreLoaded(dataBean: MutableList<HomePagerContent.DataBean>) {
        //添加数据到适配器底部
        mAdapter.addListData(dataBean)
        finishLoadMore()
    }

    override fun onLooperListLoadedList(dataBean: MutableList<HomePagerContent.DataBean>) {
        mMZBanner = headerView.findViewById(R.id.banner)

        mMZBanner.setPages(
            dataBean,
            MZHolderCreator<BannerViewHolder> { BannerViewHolder() })

        mMZBanner.start()
    }

    inner class BannerViewHolder : MZViewHolder<HomePagerContent.DataBean> {

        private lateinit var imageView: ImageView

        override fun createView(context: Context): View {
            val inflate = LayoutInflater.from(context).inflate(R.layout.banner_item, null, false)
            imageView = inflate.findViewById(R.id.banner_image)
            return inflate
        }

        override fun onBind(
            context: Context,
            position: Int,
            data: HomePagerContent.DataBean
        ) {
            // 数据绑定
            val coverPath = UrlUtils.getCoverPath(data.pict_url, 400)
            Glide.with(context).load(coverPath).into(imageView)
        }
    }

    override fun onError() {
        //网络错误
        setUpState(State.ERROR)
    }

    override fun onLoading() {
        setUpState(State.LOADING)
    }

    override fun onEmpty() {
        setUpState(State.EMPTY)
    }

    fun finishLoadMore() {
        homePagerRefresh.finishLoadmore()
    }

    override fun onPause() {
        super.onPause()
        if (::mMZBanner.isInitialized) {
            mMZBanner.pause()
        }
    }

    override fun onResume() {
        super.onResume()
        if (::mMZBanner.isInitialized) {
            mMZBanner.start()
        }
    }
}
